package com.zwx.string.leetcode_6;

/**
 * 实现strStr()
 * <p>
 * 给定一个 haystack 字符串和一个 needle 字符串，
 * 在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。
 * 如果不存在，则返回 -1
 *
 * @author 文希
 * @create 2019-07-02 0:18
 */
public class MyStrStr {

    private static int strStr(String haystack, String needle) {
        int index = 0;
        if (needle.length() == 0) {
            return 0;
        }
        if (haystack.length() == 0) {
            return -1;
        }
        while (index < haystack.length()) {

            while (index < haystack.length() && haystack.charAt(index) != needle.charAt(0)) {
                index++;
            }
            if (haystack.length() - index < needle.length()) {
                return -1;
            } else {
                if (haystack.substring(index, needle.length() + index).compareTo(needle) == 0) {
                    return index;
                } else {
                    index++;
                }
            }

        }
        if (index == haystack.length()) {
            return -1;
        } else {
            return index;
        }
    }

    public static void main(String[] args) {
        String haystack = "hello";
        String needle = "ll";
        int i = strStr(haystack, needle);
        System.out.println("i = " + i);
    }
}
